<template>
  <div :class="show ?'showMessage' : 'message' " style="width:30%" >
    <div class="message-content" :class="[getClass, 'messgae-'+StateClass]" v-show="show" >
      {{ text }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      text: '',
      timeout: null,
      StateClass: 'error'
    };
  },
  methods: {
    showMessage(text, duration = 3000, StateClass) {
      this.text = text;
      this.show = true;
      this.StateClass = StateClass ? StateClass: 'error'
      // 将消息设为自动隐藏
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.timeout = setTimeout(() => {
        this.hideMessage();
      }, duration);
    },
    hideMessage() {
      this.show = false;
      clearTimeout(this.timeout);
    },
    getClass() {
      return this.show ? 'show' : '';
    },
  }
};
</script>

<style scoped>
.message {
  position: fixed;
  top: 0%;
  left: 50%;
  transform: translateX(-50%);
}
.showMessage{
  position: fixed;
  top: 5%;
  left: 50%;
  transform: translateX(-50%);
  transition: all 0.4s;
  z-index: 9999;
}

.message-content {
  padding: 10px 20px;
  border-radius: 5px;
}
.messgae-error{
  background-color: #fef0f0;
  border: 1px solid #fef0f0;
  color: #f56c6c;
}
.messgae-success{
  background-color:#f0f9eb;
  border-color:#f0f9eb;
  color:#67C23A
}

.message-content.show {
  opacity: 1;
}
</style>